#ifndef TASK_HPP
#define TASK_HPP
#include <unistd.h>
#include <iostream>
#include <vector>
#include <functional>

using task_t =std::function<void()>; 


class TaskPool
{
    public:
        TaskPool()
        {
            srand(time(nullptr));
            _Tasks.push_back([](){
                std::cout<<"sub process[" << getpid() <<" ] 执⾏访问数据库的任务\n";
            });
            _Tasks.push_back([](){
                std::cout<<"sub process[" << getpid() <<" ] 执⾏url解析\n";
            });
            _Tasks.push_back([](){
                std::cout<<"sub process[" << getpid() <<" ] 执⾏加密任务\n";
            });
            _Tasks.push_back([](){
            std::cout<<"sub process[" << getpid() <<" ] 执⾏数据持续化任务\n";
            });
            _TaskNum=_Tasks.size();
        }
        // 实现随机选择任务码
        int SelectTasks()
        {
            return rand()%_TaskNum;
        }
        void Execut(unsigned long number )
        {
            if(number>=_TaskNum || number < 0 ) 
                return ;

            _Tasks[number]();
        }
        size_t GetTaskNum()
        {
            return _TaskNum;
        }

        void AddTask(task_t task)
        {
            _Tasks.push_back(task);
        }
        ~TaskPool(){}

    private:
        std::vector<task_t> _Tasks;
        unsigned long _TaskNum;
};

TaskPool taskPool;

void Worker()  //也可叫slaver函数，主从函数，用于子进程接受父进程任务执行   //初始任务
{
    while(true)
    {
        int cmd=0;  //任务码
        int n=::read(0,&cmd,sizeof(cmd));
        if(n==sizeof(cmd))
        {
            //执行任务
            taskPool.Execut(cmd);
        }
        else if(n==0)
        {
            std::cout<<"pid:"<<getpid()<<" exit"<<std::endl; 
            break;
        }
    }
}


#endif // TASK_HPP